package com.sunfeng.chap2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

/**
 * 验证read方法具有同步性
 */
public class Test2_4 {
    private static FileInputStream fis;

    private static FileChannel fileChannel;

    public static void main(String[] args) throws IOException, InterruptedException {
        fis = new FileInputStream(new File("d:\\a.txt"));
        fileChannel = fis.getChannel();
        Thread thread1 = new Thread() {
            @Override
            public void run() {

                try {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
                    int readLength = fileChannel.read(byteBuffer);
                    while (readLength != -1) {
                        byte[] array = byteBuffer.array();
                        System.out.println(new String(array, 0, readLength));
                        byteBuffer.clear();
                        readLength = fileChannel.read(byteBuffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread2 = new Thread() {
            @Override
            public void run() {

                try {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
                    int readLength = fileChannel.read(byteBuffer);
                    while (readLength != -1) {
                        byte[] array = byteBuffer.array();
                        System.out.println(new String(array, 0, readLength));
                        byteBuffer.clear();
                        readLength = fileChannel.read(byteBuffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread1.start();
        thread2.start();
        TimeUnit.SECONDS.sleep(3);
        fileChannel.close();
        fis.close();
    }
}
